package com.software.common;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import sun.misc.BASE64Encoder;

public class CommonUtils {
	
	public static  String getNowTime(){
		Date time = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(time);
	}
	
	public static  String getMD5(String pwd) throws NoSuchAlgorithmException
    {
      MessageDigest md = MessageDigest.getInstance("MD5");
      BASE64Encoder  base = new BASE64Encoder ();
      String pwdAfter = base.encode(md.digest(pwd.getBytes()));
      return pwdAfter;    
    }
	
	public static Object getBean(String beanName){
		XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
		return factory.getBean(beanName);
	}
	public static void outputJsonData(int success,HttpServletResponse response) throws JSONException, IOException{
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("success",success);
		
		PrintWriter pw = response.getWriter();
		pw.print(jsonObject.toString());
		pw.flush();
		pw.close();
	}
	public static void outputJsonData(String string,HttpServletResponse response) throws IOException{
		PrintWriter out=response.getWriter();
		out.write(string);
		out.flush();
		out.close();
	}
	public static  JSONObject readJSONStringFromRequestBody(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        JSONObject jsonObject = new JSONObject();
        try{
        	Map map = request.getParameterMap();
        	Iterator iterator = map.keySet().iterator();
        	while(iterator.hasNext()){
        		String key = iterator.next().toString();
        		String[] values = (String[])map.get(key);
        		jsonObject.accumulate(key, values[0]);
        	}
        }catch(Exception e){
        	
        }
        return jsonObject;
    } 
}
